import webview
import sys
import os
import time
import threading
import logging
import sqlite3
from urllib.request import urlopen
from urllib.error import URLError

# 导入Flask应用(不直接运行)
sys.path.insert(0, os.path.abspath(os.path.join(os.path.dirname(__file__), '..')))
from src.app import app, resource_path
from src.db_init import init_database

# 设置日志
logging.basicConfig(
    level=logging.INFO,
    format='%(asctime)s - %(levelname)s - %(message)s',
    handlers=[
        logging.FileHandler(os.path.join(os.path.abspath("."), 'pms_gui.log')),
        logging.StreamHandler()
    ]
)

def check_server_running():
    """检查Flask服务器是否已启动"""
    for _ in range(30):  # 尝试30次，每次等待0.5秒
        try:
            urlopen("http://127.0.0.1:5010/logintest")
            return True
        except URLError:
            time.sleep(0.5)
    return False

def start_server():
    """在后台线程中启动Flask服务器"""
    try:
        logging.info("正在启动Flask服务器...")
        # 确保实例目录存在
        instance_path = os.path.join(os.path.abspath("."), 'instance')
        if not os.path.exists(instance_path):
            os.makedirs(instance_path)

        # 日志输出
        logging.info(f"工作目录: {os.getcwd()}")
        logging.info(f"数据库路径: {resource_path('pms.db')}")
        logging.info(f"模板路径: {resource_path('templates')}")
        logging.info(f"静态文件路径: {resource_path(os.path.join('src', 'static'))}")

        # 验证模板和静态文件目录
        templates_dir = resource_path('templates')
        static_dir = resource_path(os.path.join('src', 'static'))
        if not os.path.exists(templates_dir):
            logging.error(f"模板目录不存在: {templates_dir}")
        if not os.path.exists(static_dir):
            logging.error(f"静态文件目录不存在: {static_dir}")

        # 确保数据库存在
        db_path = resource_path('pms.db')
        if not os.path.exists(db_path):
            logging.info("数据库文件不存在，正在创建...")
            conn = sqlite3.connect(db_path)
            conn.close()
            logging.info("数据库文件创建成功，准备初始化数据库...")
            if init_database():
                logging.info("数据库初始化成功")
            else:
                logging.error("数据库初始化失败")

        # 启动Flask应用，关闭debug模式以避免子进程问题
        app.run(debug=False, host='127.0.0.1', port=5010, threaded=True)
    except Exception as e:
        logging.exception(f"启动Flask服务器时出错: {str(e)}")

def create_window():
    """创建WebView窗口"""
    try:
        # 等待Flask服务器启动
        if not check_server_running():
            logging.error("Flask服务器启动失败或超时")
            webview.create_window("错误", 
                               html="<h1>服务器启动失败</h1><p>无法启动项目管理系统服务器，请检查日志。</p>")
            return

        # 创建窗口显示Flask应用
        window = webview.create_window("项目管理系统", "http://127.0.0.1:5010", 
                                     width=1280, height=800, 
                                     resizable=True, 
                                     min_size=(800, 600),
                                     confirm_close=True)
        
        # 设置窗口关闭处理
        def on_closed():
            logging.info("应用窗口已关闭，正在停止服务器...")
            os._exit(0)  # 强制退出所有线程
            
        window.events.closed += on_closed
    except Exception as e:
        logging.exception(f"创建窗口时出错: {str(e)}")

if __name__ == "__main__":
    try:
        # 在后台线程中启动Flask
        server_thread = threading.Thread(target=start_server)
        server_thread.daemon = True
        server_thread.start()
        
        # 创建GUI窗口
        logging.info("正在启动GUI窗口...")
        create_window()
        webview.start(debug=False)
    except Exception as e:
        logging.exception(f"应用启动失败: {str(e)}") 